// 污染预测模块状态管理
import { defineStore } from 'pinia'
import { pollutionApi } from '@/api/pollution.js'

export const usePollutionStore = defineStore('pollution', {
  state: () => ({
    // 化工厂数据
    factoryList: [],
    selectedFactory: null,
    
    // 预测数据
    predictionList: [],
    currentPrediction: null,
    
    // 风险评估数据
    riskAssessmentList: [],
    
    // 影响评估数据
    impactEvaluationList: [],
    
    // 加载状态
    loading: {
      factoryList: false,
      prediction: false,
      riskAssessment: false,
      impactEvaluation: false
    }
  }),
  
  getters: {
    // 获取高风险工厂
    highRiskFactories: (state) => {
      return state.factoryList.filter(factory => factory.riskLevel === 3)
    },
    
    // 获取中风险工厂
    mediumRiskFactories: (state) => {
      return state.factoryList.filter(factory => factory.riskLevel === 2)
    },
    
    // 获取低风险工厂
    lowRiskFactories: (state) => {
      return state.factoryList.filter(factory => factory.riskLevel === 1)
    },
    
    // 获取正常运行的工厂
    activeFactories: (state) => {
      return state.factoryList.filter(factory => factory.status === 1)
    },
    
    // 获取工厂总数
    totalFactories: (state) => {
      return state.factoryList.length
    },
    
    // 获取风险统计
    riskStatistics: (state) => {
      const stats = {
        high: 0,
        medium: 0,
        low: 0,
        unknown: 0
      }
      
      state.factoryList.forEach(factory => {
        switch (factory.riskLevel) {
          case 3:
            stats.high++
            break
          case 2:
            stats.medium++
            break
          case 1:
            stats.low++
            break
          default:
            stats.unknown++
        }
      })
      
      return stats
    }
  },
  
  actions: {
    // 获取化工厂列表
    async fetchFactoryList() {
      this.loading.factoryList = true
      try {
        const res = await pollutionApi.getFactoryAnalysis()
        if (res.code === 200) {
          this.factoryList = res.data
          return res.data
        } else {
          throw new Error(res.message || '获取工厂列表失败')
        }
      } catch (error) {
        console.error('获取工厂列表失败:', error)
        throw error
      } finally {
        this.loading.factoryList = false
      }
    },
    
    // 获取工厂详情
    async fetchFactoryDetail(factoryId) {
      try {
        const res = await pollutionApi.getFactoryDetail(factoryId)
        if (res.code === 200) {
          this.selectedFactory = res.data
          return res.data
        } else {
          throw new Error(res.message || '获取工厂详情失败')
        }
      } catch (error) {
        console.error('获取工厂详情失败:', error)
        throw error
      }
    },
    
    // 启动污染预测
    async startPrediction(factoryId, predictionType = 1) {
      this.loading.prediction = true
      try {
        const res = await pollutionApi.startPrediction(factoryId, predictionType)
        if (res.code === 200) {
          this.currentPrediction = res.data
          // 添加到预测列表
          this.predictionList.unshift(res.data)
          return res.data
        } else {
          throw new Error(res.message || '预测失败')
        }
      } catch (error) {
        console.error('预测失败:', error)
        throw error
      } finally {
        this.loading.prediction = false
      }
    },
    
    // 获取预测结果
    async fetchPredictionResult(predictionId) {
      try {
        const res = await pollutionApi.getPredictionResult(predictionId)
        if (res.code === 200) {
          return res.data
        } else {
          throw new Error(res.message || '获取预测结果失败')
        }
      } catch (error) {
        console.error('获取预测结果失败:', error)
        throw error
      }
    },
    
    // 获取扩散路径
    async fetchDiffusionPath(factoryId) {
      try {
        const res = await pollutionApi.getDiffusionPath(factoryId)
        if (res.code === 200) {
          return res.data
        } else {
          throw new Error(res.message || '获取扩散路径失败')
        }
      } catch (error) {
        console.error('获取扩散路径失败:', error)
        throw error
      }
    },
    
    // 生成风险评估报告
    async generateRiskAssessment(factoryId) {
      this.loading.riskAssessment = true
      try {
        const res = await pollutionApi.generateRiskAssessment(factoryId)
        if (res.code === 200) {
          this.riskAssessmentList.unshift(res.data)
          return res.data
        } else {
          throw new Error(res.message || '生成风险评估失败')
        }
      } catch (error) {
        console.error('生成风险评估失败:', error)
        throw error
      } finally {
        this.loading.riskAssessment = false
      }
    },
    
    // 获取影响评估
    async fetchImpactEvaluation(factoryId) {
      this.loading.impactEvaluation = true
      try {
        const res = await pollutionApi.getImpactEvaluation(factoryId)
        if (res.code === 200) {
          this.impactEvaluationList.unshift(res.data)
          return res.data
        } else {
          throw new Error(res.message || '获取影响评估失败')
        }
      } catch (error) {
        console.error('获取影响评估失败:', error)
        throw error
      } finally {
        this.loading.impactEvaluation = false
      }
    },
    
    // 设置选中的工厂
    setSelectedFactory(factory) {
      this.selectedFactory = factory
    },
    
    // 清除选中的工厂
    clearSelectedFactory() {
      this.selectedFactory = null
    },
    
    // 清除当前预测
    clearCurrentPrediction() {
      this.currentPrediction = null
    },
    
    // 重置状态
    reset() {
      this.factoryList = []
      this.selectedFactory = null
      this.predictionList = []
      this.currentPrediction = null
      this.riskAssessmentList = []
      this.impactEvaluationList = []
    }
  }
})
